import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Button, Form, Input, message } from 'antd'  // 新增 message 组件
import { KeyOutlined, UserOutlined } from '@ant-design/icons'
import imgLogo from '@/common/images/logo.png'
import imgCover from './cover.svg'
import { setAuthToken } from '@/router'
import './login.styl'

export default function Login() {
  const [loading, setLoading] = useState(false)
  const navigate = useNavigate()
  const [form] = Form.useForm()  // 新增 form 实例

  const onFinish = async (values) => {  // 接收表单值
    setLoading(true)
    try {
      // 发送登录请求
      const response = await fetch('http://localhost:8080/api/auth/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          username: values.username,
          password: values.password
        })
      })

      const result = await response.json()

      if (result.code === 200) {
        // 登录成功
        setAuthToken(result.data.token)
        console.log(result.data.token)
        message.success('登录成功')
        navigate('/')
      } else {
        // 登录失败
        message.error(result.message || '登录失败，请重试')
      }
    } catch (error) {
      // 网络错误处理
      console.error('登录请求失败:', error)
      message.error('网络错误，请检查连接')
    } finally {
      setLoading(false)
    }
  }

  return (
      <div className="P-login">
        <div className="login-con">
          <div className="cover-con">
            <img src={imgLogo} alt="logo" className="img-logo" />
            <h2>PT Tracker 用户登录</h2>
            <img src={imgCover} alt="" className="img-cover" />
          </div>

          <div className="pannel-con">
            <h3>Welcome!</h3>
            <p className="subtext">请登录您的账号</p>

            {/* 添加 form 属性绑定 */}
            <Form form={form} onFinish={onFinish}>
              <Form.Item
                  name="username"
                  rules={[{ required: true, message: '请输入用户名' }]}
              >
                <Input prefix={<UserOutlined />} placeholder="用户名" />
              </Form.Item>

              <Form.Item
                  name="password"
                  rules={[{ required: true, message: '请输入密码' }]}
              >
                <Input.Password prefix={<KeyOutlined />} placeholder="密码" />
              </Form.Item>

              <Button
                  type="primary"
                  htmlType="submit"
                  loading={loading}
                  block
              >
                登录
              </Button>

              <div className="action-links">
                <Button type="link" onClick={() => navigate('/register')}>
                  立即注册
                </Button>
              </div>
            </Form>
          </div>
        </div>
      </div>
  )
}